#include "bson.h"
#include "zalloc.h"
#define NULL 0
Obj* getField(BSONObj *bson, short propertyId) {
    char *data = BSONObjData(bson);
    int pos = 0;
    while (pos < BSONObjDataLength(bson)) {
	if (data[pos] == BSONOBJ) {
	    BSONObj *child = (BSONObj*)(data + pos);
	    if (BSONGetPropertyId(child) == propertyId) {
		return BSONObjData(child);
	    } else {
		pos += BSONObjLegnth(child);
	    }
	} else {
		return NULL;
	}
    }
    return NULL;
}

void addElement(BSONObj *bson, BSONObj* ele) {
    short allocatedSize = memory_size(BSONObjData(bson));
    short oldSize = BSONObjLength(bson);
    short newSize = oldSize + BSONObjLength(ele);
    char *data = BSONObjData(bson);

    if (newSize > allocatedSize) {
	BSONObjData(bson) = erealloc(data, newSize);
    }
    memcpy(BSONObjData(bson)+oldSize, ele, BSONOBJ_FIXED_LENGTH);
    memcpy(BSONObjData(bson)+oldSize+BSONOBJ_FIXED_LENGTH, BSONObjData(ele), BSONObjDataLength(ele));
}
		
void addProperty(BSONObj *bson, short propertyId, Obj *value) {
    short allocatedSize = memory_size(BSONObjData(bson));
    short oldSize = BSONObjLength(bson);
    short newSize = oldSize + ObjLength(value);
    char *data = BSONObjData(bson);
	
    if (newSize > allocatedSize) {
    	BSONObjData(bson) = erealloc(data, newSize);
    }
    BSONObj *p = (BSONObj*)(BSONObjData(bson) + oldSize);
    p->type = BSONOBJ;
    p->length = BSONOBJ_FIXED_LENGTH + ObjLength(value);
    p->propertyId = propertyId;
    memcpy(p->data, value, ObjLength(value));
}




